<?php

class ByeTyp_Action extends Typecho_Widget implements Widget_Interface_Do
{
    /**
     * 导出xml
     *
     * @access public
     * @return void
     */
    public function doExport()
    {
        $options = Helper::options();
        // execution
        $authors_list = $this->wxr_authors_list();
        $cats_list = $this->wxr_cats_list();
        $tags_list = $this->wxr_tags_list();
        $posts_list = $this->wxr_posts_list($options);

        // 备份文件名
        $fileName = 'WordPress.' . date('Y-m-d') . '.xml';

        //header('Content-Description: File Transfer');
        header('Content-Type: text/xml');
        header('Content-Disposition: attachment; filename=' . $fileName);
        if (preg_match("/MSIE ([0-9].[0-9]{1,2})/", $_SERVER['HTTP_USER_AGENT'])) {
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
        } else {
            header('Pragma: no-cache');
            header('Last-Modified: '. gmdate('D, d M Y H:i:s',
                Typecho_Date::gmtTime() + (Typecho_Date::$timezoneOffset - Typecho_Date::$serverTimezoneOffset)) . ' GMT');
        }
        header('Expires: ' . gmdate('D, d M Y H:i:s',
            Typecho_Date::gmtTime() + (Typecho_Date::$timezoneOffset - Typecho_Date::$serverTimezoneOffset)) . ' GMT');

        echo '<?xml version="1.0" encoding="'.$options->charset.'" ?>' . "\n";
        echo <<< EOT
<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->
<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->
<!-- You may use this file to transfer that content from one site to another. -->
<!-- This file is not intended to serve as a complete backup of your site. -->

<!-- To import this information into a WordPress site follow these steps: -->
<!-- 1. Log in to that site as an administrator. -->
<!-- 2. Go to Tools: Import in the WordPress admin panel. -->
<!-- 3. Install the "WordPress" importer from the list. -->
<!-- 4. Activate & Run Importer. -->
<!-- 5. Upload this file using the form provided on that page. -->
<!-- 6. You will first be asked to map the authors in this export file to users -->
<!--    on the site. For each author, you may choose to map to an -->
<!--    existing user on the site or to create a new user. -->
<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->
<!--    contained in this file into your site. -->
<rss version="2.0"
	xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:wp="http://wordpress.org/export/1.2/"
>
<channel>
    <title>$options->title</title>
    <link>$options->siteUrl</link>
	<description>$options->description</description>
	<pubDate>Wed, 19 Nov 2014 06:15:10 +0000</pubDate>
	<language>$options->lang</language>
	<wp:wxr_version>1.2</wp:wxr_version>
	<wp:base_site_url>$options->siteUrl</wp:base_site_url>
	<wp:base_blog_url>$options->siteUrl</wp:base_blog_url>
	$authors_list
	$cats_list
	$tags_list
	<generator>http://wordpress.org/?v=4.0</generator>
	$posts_list
</channel>
</rss>
EOT;
    }

    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
        $this->widget('Widget_User')->pass('administrator');
        $this->on($this->request->is('export'))->doExport();
    }

    /**
     * Output list of authors
     */
    public function wxr_authors_list()
    {
        $db = Typecho_Db::get();
        $dbPrefix = $db->getPrefix();

        $user_table = $dbPrefix . 'users';
        $authors = $db->fetchAll($db->query("select uid,name,mail from {$user_table} where activated != 0"));
        $html = '';
        foreach ( $authors as $author ) {
            $html .= "\t<wp:author>";
            $html .= '<wp:author_id>' . $author['uid'] . '</wp:author_id>';
            $html .= '<wp:author_login>' . $author['name'] . '</wp:author_login>';
            $html .= '<wp:author_email>' . $author['mail'] . '</wp:author_email>';
            $html .= '<wp:author_display_name>' . $this->wxr_cdata($author['name']) . '</wp:author_display_name>';
            $html .= '<wp:author_first_name>' . $this->wxr_cdata('') . '</wp:author_first_name>';
            $html .= '<wp:author_last_name>' . $this->wxr_cdata('') . '</wp:author_last_name>';
            $html .= "</wp:author>\n";
        }
        return $html;
    }

    public function wxr_cats_list()
    {
        $db = Typecho_Db::get();
        $dbPrefix = $db->getPrefix();
        $html = '';
        $table_name = $dbPrefix . 'metas';
        $sql = "select a.mid, a.name, a.slug, a.description, b.name parent
        from {$table_name} a
        left join {$table_name} b
        on a.mid = b.parent
        where a.type = 'category'";
        $rows = $db->fetchAll($db->query($sql));
        foreach ($rows as $row) {
            $html .= "<wp:category><wp:term_id>{$row['mid']}</wp:term_id><wp:category_nicename>{$row['slug']}</wp:category_nicename><wp:category_parent>{$row['parent']}</wp:category_parent><wp:cat_name><![CDATA[{$row['name']}]]></wp:cat_name></wp:category>\n";
        }
        return $html;
    }

    public function wxr_tags_list()
    {
        $db = Typecho_Db::get();
        $dbPrefix = $db->getPrefix();
        $html = '';
        $table_name = $dbPrefix . 'metas';
        $sql = "select mid, name, slug, description
        from {$table_name}
        where type = 'tag'";
        $rows = $db->fetchAll($db->query($sql));
        foreach ($rows as $row) {
            $html .= "<wp:tag><wp:term_id>{$row['mid']}</wp:term_id><wp:tag_slug>{$row['slug']}</wp:tag_slug><wp:tag_name><![CDATA[{$row['name']}]]></wp:tag_name></wp:tag>\n";
        }
        return $html;
    }

    public function wxr_posts_list($options)
    {
        $db = Typecho_Db::get();
        $dbPrefix = $db->getPrefix();
        $html = '';
        $post_table = $dbPrefix . 'contents';
        $relation_table = $dbPrefix . 'relationships';
        $meta_table = $dbPrefix . 'metas';
        $user_table = $dbPrefix . 'users';

        $sql = "select p.*,
                group_concat(concat(m.name, '@', m.slug, '@', m.type) separator '|') terms,
                u.name author
                from {$post_table} p
                left join {$relation_table} r
                on p.cid = r.cid
                left join {$meta_table} m
                on r.mid = m.mid
                left join {$user_table} u
                on p.authorId = u.uid
                group by p.cid";
        $rows = $db->fetchAll($db->query($sql));
        foreach ($rows as $row) {
            $pub_date = gmdate(DATE_RFC2822, $row['created']);
            $post_date = date('Y-m-d H:i:s', $row['created']);
            $tag_str = '';
            $cat_str = '';
            $post_meta = '';
            $comment_str = $this->get_comments($row['cid']);
            if ($row['type'] == 'page') {
                $post_meta = "<wp:postmeta>
                                <wp:meta_key>_wp_page_template</wp:meta_key>
                                <wp:meta_value><![CDATA[default]]></wp:meta_value>
                            </wp:postmeta>";
            } else {
                if ($row['terms']) {
                    $terms_arr = explode('|', $row['terms']);
                    foreach ($terms_arr as $term) {
                        $temp = explode('@', $term);
                        $t_name = $temp[0];
                        $t_slug = $temp[1];
                        $t_type = $temp[2];
                        if ($t_type == 'tag') {
                            $tag_str .= "<category domain=\"post_tag\" nicename=\"{$t_slug}\"><![CDATA[{$t_name}]]></category>\n";
                        } else if ($t_type == 'category') {
                            $cat_str .= "<category domain=\"category\" nicename=\"{$t_slug}\"><![CDATA[{$t_name}]]></category>\n";
                        } else {}
                    }
                }
            }
            // 处理markdown,判断是否是markdown
            $version_string = Typecho_Common::VERSION;
            $args = explode('/', $version_string);
            $version = floatval($args[0]);
            if (substr($row['text'], 0, 15) == '<!--markdown-->' && $version >= 1.0) {
                //$parser = new Parser();
                //$content = $parser->makeHtml($row['text']);
                $content = Markdown::convert($row['text']);
            } else {
                $content = $row['text'];
            }
            $html .= "
            <item>
                <title>{$row['title']}</title>
                <link>{$options->siteUrl}?p={$row['cid']}</link>
                <pubDate>{$pub_date}</pubDate>
                <dc:creator><![CDATA[{$row['author']}]]></dc:creator>
                <guid isPermaLink=\"false\">{$options->siteUrl}?p={$row['cid']}</guid>
                <description></description>
                <content:encoded><![CDATA[{$content}]]></content:encoded>
                <excerpt:encoded><![CDATA[]]></excerpt:encoded>
                <wp:post_id>{$row['cid']}</wp:post_id>
                <wp:post_date>{$post_date}</wp:post_date>
                <wp:post_date_gmt>{$post_date}</wp:post_date_gmt>
                <wp:comment_status>open</wp:comment_status>
                <wp:ping_status>open</wp:ping_status>
                <wp:post_name>{$row['slug']}</wp:post_name>
                <wp:status>{$row['status']}</wp:status>
                <wp:post_parent>{$row['parent']}</wp:post_parent>
                <wp:menu_order>0</wp:menu_order>
                <wp:post_type>{$row['type']}</wp:post_type>
                <wp:post_password>{$row['password']}</wp:post_password>
                <wp:is_sticky>0</wp:is_sticky>
                {$post_meta}
                {$cat_str}
                {$tag_str}
                {$comment_str}
            </item>";
        }
        return $html;
    }

    public function get_comments($cid)
    {
        $html = '';
        $db = Typecho_Db::get();
        $dbPrefix = $db->getPrefix();
        $comment_table = $dbPrefix . 'comments';

        $sql = "select * from {$comment_table} where cid = {$cid}";
        $rows = $db->fetchAll($db->query($sql));
        if (count($rows) > 0) {
            foreach ($rows as $c) {

                $co_date = date('Y-m-d H:i:s', $c['created']);

                switch($c['status']) {
                    case 'approved':
                        $status = 1;
                        break;
                    case 'spam':
                        $status = 'spam';
                        break;
                    case 'waiting':
                        $status = 0;
                        break;
                    case 'hidden':
                        $status = 0;
                        break;
                }
                $html .= "
                <wp:comment>
                    <wp:comment_id>{$c['coid']}</wp:comment_id>
                    <wp:comment_author><![CDATA[{$c['author']}]]></wp:comment_author>
                    <wp:comment_author_email>{$c['mail']}</wp:comment_author_email>
                    <wp:comment_author_url>{$c['url']}</wp:comment_author_url>
                    <wp:comment_author_IP>{$c['ip']}</wp:comment_author_IP>
                    <wp:comment_date>{$co_date}</wp:comment_date>
                    <wp:comment_date_gmt>{$co_date}</wp:comment_date_gmt>
                    <wp:comment_content><![CDATA[{$c['text']}]]></wp:comment_content>
                    <wp:comment_approved>{$status}</wp:comment_approved>
                    <wp:comment_type>{$c['type']}</wp:comment_type>
                    <wp:comment_parent>{$c['parent']}</wp:comment_parent>
                    <wp:comment_user_id>{$c['authorId']}</wp:comment_user_id>
                </wp:comment>";
            }
        }
        return $html;
    }

    public function wxr_cdata( $str ) {
        $str = '<![CDATA[' . str_replace( ']]>', ']]]]><![CDATA[>', $str ) . ']]>';
        return $str;
    }
}